import { Picker, Text, View } from '@tarojs/components'
import { Component } from '@tarojs/taro'
import { AtAccordion, AtButton, AtDivider, AtFab, AtFloatLayout, AtInput, AtList, AtListItem, AtSwitch, AtToast } from 'taro-ui'
import { NoteItem } from './note-item'

const show = require('../../utils/show.js')
const http = require('../../utils/http.js')
const format = require('../../utils/format.js')
const constant = require('../../utils/constant.js')

export default class Index extends Component {
    config = {
        navigationBarTitleText: '极简笔记'
    }

    constructor(props) {
        super(props)
        this.state = {
            loading: false,
            isWaitReview: true,
            isShowCreate: false,
            dateStr: format.dateYmd(new Date()),
            noteId: 0,
            data: [],
            hiddenItem: true
        }
    }

    componentDidShow() {
        this.onSearch()
    }
    componentDidMount() { }

    // --- 显示
    showList = () => {
        this.setState({ hiddenItem: true })
        this.onSearch()
    }
    showItem = (reviewId, noteId) => {
        this.setState({ hiddenItem: false, noteId })
        this.noteItemRef.findItemInfo(reviewId, noteId, this.state.isWaitReview)
    }

    // --- 上一页、下一页
    showPrevious = () => {
        this.updateToReviewed(-1)
    }
    showNext = () => {
        this.updateToReviewed(+1)
    }
    updateToReviewed = (sign) => {
        let arr = []
        this.state.data.forEach(type => { arr = [...arr, ...type.notes] })
        let curIndex = arr.findIndex(note => note.noteId == this.state.noteId)
        if (sign > 0 && curIndex + 1 == arr.length) {
            show.info('已是最后一项')
            if (this.state.isWaitReview) {
                this.fetchNotReview()
            }
            return
        } else if (sign < 0 && curIndex == 0) {
            show.info('已是第一项')
            return
        }
        let reviewNote = arr[curIndex + sign]
        this.showItem(reviewNote.reviewId, reviewNote.noteId)
    }
    fetchNotReview = () => {
        http.get('/api/note/review/find-not-review-recent-date', {}, res => {
            let date = res.map.recent_date
            if (date && date !== this.state.dateStr) {
                show.confirm({
                    title: `【${date}】还有笔记待复习`,
                    content: '是否直接跳转',
                    onOk: () => {
                        this.setState({ dateStr: date }, this.showList)
                    }
                })
            }
        })
    }

    // --- 搜索
    onDateChange = (e) => {
        this.setState({ dateStr: e.detail.value }, this.onSearch)
    }
    onStatusChange = (isWaitReview) => {
        this.setState({ isWaitReview }, this.onSearch)
    }
    onSearch = () => {
        this.setState({ loading: true })
        let reviewStatus = this.state.isWaitReview ? 1 : 2
        http.get2('/api/note/review/find-list', { status: reviewStatus, date: this.state.dateStr })
            .then(res => {
                let now = format.dateYmd(new Date())
                let isShowCreate = this.state.isWaitReview && now == this.state.dateStr && !res[0]
                this.setState({ loading: false, data: res, isShowCreate })
            })
            .catch(e => {
                this.setState({ loading: false })
            })
    }
    onMoreButtonClick = (index) => {
        let urls = [
            `/pages/type/type-list`,
            `/pages/note/note-edit`,
            `/pages/stats/stats`,
            constant.PAGE_LOGIN,
        ]
        if (index == 3) {
            show.confirm({
                title: '退出提醒',
                content: '确认是否退出？',
                onOk: () => {
                    Taro.removeStorageSync(constant.USER_TOKEN_KEY)
                    Taro.redirectTo({ url: urls[index] })
                }
            })
        } else {
            Taro.navigateTo({ url: urls[index] })
        }
        this.setState({ moreOpBtn: false })
    }
    copyWebsite = () => {
        Taro.setClipboardData({ data: constant.WEBSITE }).then(() => {
            Taro.showToast({ title: '链接已复制' })
        })
    }

    render() {
        return (
            <View>
                <AtToast isOpened={this.state.loading} text='加载中' icon='loading'></AtToast>
                <View hidden={!this.state.hiddenItem}>
                    <View>
                        <AtAccordion
                            title='搜索-复习计划'
                            icon={{ value: 'search', size: '15' }}
                            open={this.state.searchOpen}
                            onClick={(v) => this.setState({ searchOpen: v })}
                        >
                            <Picker mode='date' onChange={this.onDateChange}>
                                <AtList>
                                    <AtListItem title='日期' extraText={this.state.dateStr} />
                                </AtList>
                            </Picker>
                            <AtSwitch
                                title={this.state.isWaitReview ? '待复习' : '已复习'}
                                checked={true}
                                onChange={this.onStatusChange} />
                        </AtAccordion>
                    </View>
                    {
                        this.state.data.map(type => {
                            return (
                                <View key={'type-' + type.typeId}>
                                    <AtDivider content={`【${type.typeName}】`} > </AtDivider>
                                    <AtList hasBorder={false} >
                                        {
                                            type.notes.map(note => {
                                                return (
                                                    <AtListItem key={'note-' + note.noteId}
                                                        title={note.noteTitle}
                                                        onClick={() => this.showItem(note.reviewId, note.noteId)}
                                                        arrow='right' />
                                                )
                                            })
                                        }
                                    </AtList>
                                </View>
                            )
                        })
                    }
                    {
                        this.state.isShowCreate ?
                            (
                                <View style={{ marginTop: '240rpx', textAlign: 'center', width: '100%', padding: '20rpx' }}>
                                    <View style={{ marginBottom: '0rpx' }}>当前没有可复习的笔记</View>
                                    <View style={{ marginTop: '20rpx', marginBottom: '10rpx' }}>
                                        <View className='at-article'>
                                            <View className='at-article__p'>
                                                创建笔记请访问官网：
                                            </View>
                                            <View className='at-article__p' style={{ color: '#FF00EF' }} onClick={this.copyWebsite}>
                                                {constant.WEBSITE}
                                            </View>
                                        </View>
                                    </View>
                                    {/* <AtButton type='primary' onClick={() => this.onMoreButtonClick(1)}> 创建笔记 </AtButton> */}
                                </View>
                            )
                            : null
                    }
                    <View style={{ position: 'fixed', bottom: '30rpx', right: '30rpx' }}>
                        <AtFab onClick={() => this.setState({ moreOpBtn: true })}>
                            <Text className='at-fab__icon at-icon at-icon-menu'></Text>
                        </AtFab>
                    </View>
                    <AtFloatLayout title='更多操作' isOpened={this.state.moreOpBtn} onClose={() => this.setState({ moreOpBtn: false })} >
                        <View style={{ marginTop: '10rpx' }}>
                            <AtButton type='primary' onClick={() => this.onMoreButtonClick(0)}> 分类管理 </AtButton>
                        </View>
                        {/* <View style={{ marginTop: '10rpx' }}>
                            <AtButton type='primary' onClick={() => this.onMoreButtonClick(1)}> 创建笔记 </AtButton>
                        </View> */}
                        <View style={{ marginTop: '10rpx' }}>
                            <AtButton type='primary' onClick={() => this.onMoreButtonClick(2)}> 系统统计 </AtButton>
                        </View>
                        <View style={{ marginTop: '80rpx' }}>
                            <AtButton type='primary' onClick={() => this.onMoreButtonClick(3)}> 退出系统 </AtButton>
                        </View>
                    </AtFloatLayout>
                </View>
                <View hidden={this.state.hiddenItem}>
                    <NoteItem
                        ref={(ref) => { this.noteItemRef = ref }}
                        showList={this.showList}
                        showPrevious={this.showPrevious}
                        showNext={this.showNext}
                    />
                </View>
            </View>
        )
    }
}
